package servlet;

import biz.EmpBiz;
import biz.impl.EmpBizImpl;
import org.example.bean.EmpInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/emp3")
public class EmpServlet extends HttpServlet {
    private EmpBiz eb = new EmpBizImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        if (null == type || "find".equals(type)) {
            find(request, response);
        } else if ("id".equals(type)) {
            id(request, response);
        }else if ("update".equals(type)){
            update(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s = request.getParameter("page");
        int page = Integer.parseInt(s == null ? "1" : s);
        List<EmpInfo> list = eb.findEmpByPage(page);
        request.getSession().setAttribute("ALL_EMP_LIST", list);
        request.getSession().setAttribute("ALL_PAGE", eb.findEmpAllCount());
        response.sendRedirect("index.jsp");
    }
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmpInfo ei = new EmpInfo();
        int  empNo = Integer.parseInt(request.getParameter("empNo"));
        int  mgr = Integer.parseInt(request.getParameter("mgr"));
        double sal = Double.parseDouble(request.getParameter("sal"));
        double comm = Double.parseDouble(request.getParameter("comm"));
        String ename = request.getParameter("ename");
        String job = request.getParameter("job");
        String hireDate = request.getParameter("hireDate");
        ei.setEmpNo(empNo);
        ei.setEname(ename);
        ei.setJob(job);
        ei.setMgr(mgr);
        ei.setHireDate(hireDate);
        ei.setSal(sal);
        ei.setComm(comm);
        eb.updateEmp(ei);
        find(request,response);

    }

    protected void id(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s = request.getParameter("empno");
        int id = Integer.parseInt(s);
        request.getSession().setAttribute("EMP_INFO",eb.findEmpById(id));
        response.sendRedirect("update.jsp");
    }
}